package com.mentalhealthplatform.schoolV1.service;

import com.mentalhealthplatform.appModels.Student;
import com.mentalhealthplatform.exception.others.ResourceNotFoundException;
import com.mentalhealthplatform.exception.user.UserAlreadyExistsException;
import com.mentalhealthplatform.global.rbac.model.User;
import com.mentalhealthplatform.global.rbac.service.entity.BaseUserService;
import com.mentalhealthplatform.schoolV1.dto.StudentDTO;
import com.mentalhealthplatform.schoolV1.repository.StudentRepositoryV1;
import com.mentalhealthplatform.utils.PagedResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class StudentServiceV1 {

    private static final Logger logger = LoggerFactory.getLogger(StudentServiceV1.class);

    @Autowired
    private BaseUserService baseUserService;

    @Autowired
    private StudentRepositoryV1 studentRepositoryV1;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 获取所有学生信息（分页、过滤、排序）
    public PagedResponse<StudentDTO> getStudents(String name, String major, String college, String gender,
                                                 LocalDateTime startDate, LocalDateTime endDate,
                                                 Pageable pageable) {

        // 使用 StudentRepository 进行分页查询
        Page<Student> studentsPage = studentRepositoryV1.findByFilters(name, major, college, gender, startDate, endDate, pageable);

        // 将 Student 实体转换为 StudentDTO
        List<StudentDTO> studentDTOs = studentsPage.getContent().stream()
                .map(StudentDTO::convertToDTO)
                .collect(Collectors.toList());

        // 创建并返回分页响应
        return new PagedResponse<>(studentDTOs, studentsPage.getNumber(), studentsPage.getSize(),
                studentsPage.getTotalElements(), studentsPage.getTotalPages(), studentsPage.isLast());
    }

    // 根据学生ID获取学生信息
    public StudentDTO getStudentById(UUID studentId) {
        Student student = studentRepositoryV1.findById(studentId)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with id " + studentId));
        return StudentDTO.convertToDTO(student);
    }

    // 根据学号获取学生信息
    public StudentDTO getStudentByNumber(String number) {
        Student student = studentRepositoryV1.findByNumber(number)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with number " + number));
        return StudentDTO.convertToDTO(student);
    }

    // 添加新学生
    public StudentDTO addStudent(StudentDTO studentDTO) {
        // 通过 username 查找是否已有该用户
        Optional<User> userOptional = baseUserService.findByUsername(studentDTO.getNumber());

        // 如果用户不存在，创建新用户
        if (userOptional.isEmpty()) {

            studentDTO.setUsername(studentDTO.getNumber());

            // 将 StudentDTO 转换为 Student 实体
            Student student = studentDTO.convertToEntity();

            // 默认密码
            student.setPassword(passwordEncoder.encode("123456"));

            // 保存 Student 实体（JPA 会处理继承关系）
            Student savedStudent = studentRepositoryV1.save(student);

            // 返回保存后的 StudentDTO
            return StudentDTO.convertToDTO(savedStudent);
        } else {
            // 如果用户已经存在，抛出自定义异常
            throw new UserAlreadyExistsException("该学号已录入: " + studentDTO.getNumber());
        }
    }

    // 更新学生信息
    public StudentDTO updateStudent(UUID studentId, StudentDTO studentDTO) {
        Student student = studentRepositoryV1.findById(studentId)
                .orElseThrow(() -> new ResourceNotFoundException("Student not found with id " + studentId));

        student.setUsername(studentDTO.getUsername());
        student.setPhone(studentDTO.getPhone());
        student.setStatus(studentDTO.isStatus());
        student.setMajor(studentDTO.getMajor());
        student.setCollege(studentDTO.getCollege());
        student.setAddress(studentDTO.getAddress());
        student.setBirthDate(studentDTO.getBirthDate());
        student.setName(studentDTO.getName());
        student.setNumber(studentDTO.getNumber());
        student.setGender(studentDTO.getGender());
        student.setGrade(studentDTO.getGrade());

        Student updatedStudent = studentRepositoryV1.save(student);
        return StudentDTO.convertToDTO(updatedStudent);
    }

    // 删除学生
    public void deleteStudent(UUID studentId) {
        studentRepositoryV1.deleteById(studentId);
    }

    // 批量删除学生
    public void batchDeleteStudents(List<UUID> ids) {
        studentRepositoryV1.deleteAllByIdIn(ids);
    }
}
